/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package filesecurity;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.crypto.SecretKey;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author lehoangkhanh
 */
public class EncryptForm extends javax.swing.JInternalFrame {

    /**
     * Creates new form EncyptForm
     */
    MainFrame rootFrame = null;
    User selectUser = null;
    String fileName = null;
    String filePath = null;
    public EncryptForm(MainFrame root) {
        initComponents();
        rootFrame = root;
        algo.addItem("DES");
        algo.addItem("AES");
        HashMap<String, User> list = rootFrame.getUserList();
        Set receiverlist = list.keySet();
        Iterator i = receiverlist.iterator();
        while(i.hasNext()){
            String email = (String)i.next();
            receiver.addItem(email);
        }    
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        receiver = new javax.swing.JComboBox();
        jToggleButton1 = new javax.swing.JToggleButton();
        jLabel3 = new javax.swing.JLabel();
        savein = new javax.swing.JToggleButton();
        algo = new javax.swing.JComboBox();

        setClosable(true);
        setIconifiable(true);
        setTitle("Encrypt Info");

        jLabel1.setText("Algorithm:");

        jLabel2.setText("Receiver:");

        jToggleButton1.setText("OK<<");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Save in:");

        savein.setText("...");
        savein.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveinMouseClicked(evt);
            }
        });
        savein.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveinActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(16, 16, 16)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(algo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(receiver, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(savein, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(144, Short.MAX_VALUE)
                .addComponent(jToggleButton1)
                .addGap(123, 123, 123))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(algo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(receiver, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(savein))
                .addGap(18, 18, 18)
                .addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveinActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_saveinActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        // TODO add your handling code here:
        int algokey = 0;
        if(algo.getSelectedItem().equals("DES")){
            algokey = 1;
        }
        if(algo.getSelectedItem().equals("AES")){
            algokey = 2;
        }
        if(fileName==null || fileName.equals("")){
            JOptionPane.showMessageDialog(rootPane, "Please select location of output file!!!");
            return;
        }
        User selectedUser = (User)rootFrame.getUserList().get(receiver.getSelectedItem().toString());
        byte[] data = Utils.readFile(rootFrame.getFilePath());
        SecretKey secretKey = KeyFac.secretKeyGen(algokey);
        byte[] iv = Crypto.getIV(algokey);
        byte[] encryptedData = Crypto.encryptFile(data, secretKey, algokey, iv);
        byte[] encryptedKey = Crypto.encryptKey(secretKey, selectedUser.getPublicKey());
        byte[] file = Utils.addHeader(encryptedData, algokey, encryptedKey.length, encryptedKey, iv);
        if(iv!=null && encryptedData!=null && encryptedKey!=null && file!= null){
            Utils.writeFile(file, filePath+"/"+fileName);
            JOptionPane.showMessageDialog(rootPane, "Encrypt file successful!!!");
            this.setVisible(false);
            return;
        }
        JOptionPane.showMessageDialog(rootPane, "Error!!! Please try again");
    }//GEN-LAST:event_jToggleButton1ActionPerformed

    private void saveinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveinMouseClicked
        // TODO add your handling code here:
        JFileChooser file = new JFileChooser();
        file.setSelectedFile(new File(rootFrame.getFileName()+".encrypted"));
        int op = file.showSaveDialog(null);
        if(op == JFileChooser.APPROVE_OPTION){
            filePath = file.getCurrentDirectory().getPath().toString();
            fileName = file.getSelectedFile().getName();
            savein.setText("Just Selected...");
            savein.setToolTipText(filePath);
        }
    }//GEN-LAST:event_saveinMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox algo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JComboBox receiver;
    private javax.swing.JToggleButton savein;
    // End of variables declaration//GEN-END:variables
}
